package edu.ccut.saturn.studio.dialog.saturndatamapping;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseTrackAdapter;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import edu.ccut.saturn.studio.Activator;
import edu.ccut.saturn.studio.Images;
import edu.ccut.saturn.studio.core.search.SaturnFileSearcher.SearchResult;
import edu.ccut.saturn.studio.core.search.dialog.OneCompontentSearchDialog;
import edu.ccut.saturn.studio.core.util.eclipse.Messages;
import edu.ccut.saturn.studio.core.util.eclipse.SaturnValidation;
import edu.ccut.saturn.studio.core.util.xml.SaturnW3CUtil;
import edu.ccut.saturn.studio.dialog.SelectionCandidate;
import edu.ccut.saturn.studio.dialog.TableViewerContentProvider;
import edu.ccut.saturn.studio.dialog.TableViewerLableProvider;
import edu.ccut.saturn.studio.logic.model.Shape;
import edu.ccut.saturn.studio.logic.model.ShapesDiagram;
import edu.ccut.saturn.studio.logic.model.saturn.SaturnDataMapping;
import edu.ccut.saturn.studio.logic.model.saturn.SaturnMappingRule;
import edu.ccut.saturn.studio.logic.model.saturn.SaturnParameter;

public class SaturnDataMappingDialog extends TitleAreaDialog {

	private Text idText;
	private Text text;
	private Table table_1;
	private Table table;
	private Text textTargetKey;
	private Combo comboTarget;
	private Text textSourceKey;
	private Combo comboSource;
	private Text textName;
	private SaturnDataMapping shape;
	private List<SaturnMappingRule> mappingSources;
	private List<SaturnMappingRule> mappingTarget;
	private TableViewer tableViewer;
	private TableViewer tableViewer1;
	private Button buttonAuto;
	private Button buttonUserDefine;

	private String project = null;

	private String parameter[] = new String[] { "sqldata", "saturndata" };

	private List<Document> sqldata = null;

	public SaturnDataMappingDialog(Shell parentShell, SaturnDataMapping shape) {
		super(parentShell);
		this.shape = shape;
		mappingSources = copyList(shape.getSaturnMappingSource());
		mappingTarget = copyList(shape.getSaturnMappingRules());
	}

	protected Control createContents(Composite parent) {
		Control contents = super.createContents(parent);
		setMessage(SelectionCandidate.SETTING_ATTRIBUTE + shape.getName());
		return contents;
	}

	protected Control createDialogArea(Composite parent) {
		Composite area = (Composite) super.createDialogArea(parent);
		Composite container = new Composite(area, SWT.NONE);
		final GridLayout gridLayout = new GridLayout();
		gridLayout.numColumns = 5;
		container.setLayout(gridLayout);
		final GridData gd_container = new GridData(SWT.FILL, SWT.FILL, false,
				false);
		gd_container.heightHint = 571;
		gd_container.widthHint = 631;
		container.setLayoutData(gd_container);

		final Label idLabel = new Label(container, SWT.NONE);
		idLabel.setText("ID");

		idText = new Text(container, SWT.READ_ONLY | SWT.BORDER);
		final GridData gd_idText = new GridData(SWT.FILL, SWT.CENTER, true, false);
		idText.setLayoutData(gd_idText);
		new Label(container, SWT.NONE);
		new Label(container, SWT.NONE);
		new Label(container, SWT.NONE);

		final Label label = new Label(container, SWT.NONE);
		final GridData gd_label = new GridData();
		gd_label.verticalIndent = 5;
		label.setLayoutData(gd_label);
		label.setText(Messages.getString("SaturnDataMappingDialog.name")); //$NON-NLS-1$

		textName = new Text(container, SWT.BORDER);
		textName.setTextLimit(50);
		final GridData gd_textName = new GridData(SWT.RIGHT, SWT.CENTER, true,
				false);
		gd_textName.widthHint = 300;
		gd_textName.verticalIndent = 5;
		textName.setLayoutData(gd_textName);
		final Label label_9 = new Label(container, SWT.NONE);
		label_9.setLayoutData(new GridData());
		label_9
				.setText(Messages
						.getString("SaturnDataMappingDialog.decription")); //$NON-NLS-1$

		text = new Text(container, SWT.BORDER);
		text.setTextLimit(200);
		final GridData gd_text = new GridData(SWT.FILL, SWT.CENTER, true, false);
		gd_text.widthHint = 239;
		text.setLayoutData(gd_text);
		new Label(container, SWT.NONE);

		final Label label_4 = new Label(container, SWT.NONE);
		final GridData gd_label_4 = new GridData();
		gd_label_4.verticalIndent = 5;
		label_4.setLayoutData(gd_label_4);
		label_4.setText(Messages.getString("SaturnDataMappingDialog.target")); //$NON-NLS-1$
		comboTarget = new Combo(container, SWT.NONE);
		comboTarget.setTextLimit(100);
		// comboTarget.addModifyListener(new ModifyListener() {
		// public void modifyText(final ModifyEvent e) {
		// String value = comboTarget.getText().trim();
		// if(value.contains("edu.ccut.saturn.component.SaturnData")){
		// if("".equals(textTargetKey.getText().trim())||textTargetKey.getText()==null){
		// setErrorMessage(Messages.getString("SaturnDataMappingDialog.31"));
		// getButton(IDialogConstants.OK_ID).setEnabled(false);
		// }
		// }
		// else{
		// setErrorMessage(null);
		// if(getButton(IDialogConstants.OK_ID)!=null){
		// getButton(IDialogConstants.OK_ID).setEnabled(true);
		// }
		// }
		// }
		// });
		final GridData gd_comboTarget = new GridData(SWT.RIGHT, SWT.CENTER,
				true, false);
		gd_comboTarget.widthHint = 280;
		gd_comboTarget.verticalIndent = 5;
		comboTarget.setLayoutData(gd_comboTarget);

		this.comboTarget.setText(shape.getValuekey());

		final Label label_5 = new Label(container, SWT.NONE);
		final GridData gd_label_5 = new GridData();
		gd_label_5.verticalIndent = 5;
		label_5.setLayoutData(gd_label_5);
		label_5.setText(Messages
				.getString("SaturnDataMappingDialog.TargetFullyKey")); //$NON-NLS-1$

		textTargetKey = new Text(container, SWT.BORDER);
		textTargetKey.setTextLimit(100);
		final GridData gd_textTargetKey = new GridData(SWT.FILL, SWT.CENTER,
				true, false);
		gd_textTargetKey.widthHint = 265;
		gd_textTargetKey.verticalIndent = 5;
		textTargetKey.setLayoutData(gd_textTargetKey);
		this.textTargetKey.setText(shape.getFullkey());

		final Label browseTarget = new Label(container, SWT.NONE);
		browseTarget.setImage(Activator.getImage(Images.AMPLIFY_PLUS));
		final GridData gd_browseTarget = new GridData();
		gd_browseTarget.verticalIndent = 5;
		browseTarget.setLayoutData(gd_browseTarget);
		browseTarget.addMouseTrackListener(new MouseTrackAdapter() {
			public void mouseEnter(final MouseEvent e) {
				browseTarget.setImage(Activator.getImage(Images.AMPLIFY_MINUS));
			}

			public void mouseExit(final MouseEvent e) {
				browseTarget.setImage(Activator.getImage(Images.AMPLIFY_PLUS));
			}
		});
		browseTarget.addMouseListener(new MouseAdapter() {
			public void mouseDown(final MouseEvent e) {

				// ElementListSelectionDialog projectsDialog = new
				// ElementListSelectionDialog(
				// Display.getDefault().getShells()[0],
				// new SaturnSWTUtils.SaturnLabelDefaultProvider());
				// IProject projects[] =
				// ResourcesPlugin.getWorkspace().getRoot()
				// .getProjects();
				//
				// projectsDialog.setTitle(Messages.getString("SaturnDataMappingDialog.ChooseOneProject"));
				// //$NON-NLS-1$
				//
				// List<String> projectsName = new ArrayList<String>();
				//
				// for (IProject project : projects) {
				// projectsName.add(project.getName());
				// }
				//
				// projectsDialog.setElements(projectsName
				// .toArray(new String[] {}));
				//
				// if (projectsDialog.open() == Window.OK) {
				// project = (String) projectsDialog.getFirstResult();
				// }
				//
				// if (project == null || project.equals("")) {
				// return;
				// }
				//
				// ElementListSelectionDialog dialog1 = new
				// ElementListSelectionDialog(
				// Display.getDefault().getShells()[0],
				// new SaturnSWTUtils.SaturnLabelDefaultProvider());
				//
				// IRunnableWithProgress op = new IRunnableWithProgress() {
				// public void run(IProgressMonitor monitor)
				// throws InvocationTargetException {
				// monitor.beginTask("please wait", 100);
				// GUIUpdater g = new GUIUpdater(monitor);
				// Thread t = new Thread(g);
				// sqldata = null;
				// t.start();
				// sqldata = SearchFile.searchFileInproject(
				// ResourcesPlugin.getWorkspace().getRoot()
				// .getProject(project), parameter);
				// }
				// };
				// try {
				// new ProgressMonitorDialog(getShell()).run(true, false, op);
				// } catch (Exception e1) {
				// }
				//
				// Map<String, List<Node>> map = findSaturnData(sqldata);
				// Set<String> set = map.keySet();
				// dialog1.setElements(set.toArray(new String[0]));
				// if (dialog1.open() == Window.OK) {
				// String ddd = (String) dialog1.getFirstResult();
				// textTargetKey.setText(ddd);
				// setErrorMessage(null);
				// getButton(IDialogConstants.OK_ID).setEnabled(true);
				// List<Node> list = map.get(ddd);
				// mappingTarget.removeAll(mappingTarget);
				// for (Node node : list) {
				// String columnAlias = SaturnW3CUtil
				// .getNodeAttributeValue(node, "columnAlias");
				// String name = SaturnW3CUtil.getNodeAttributeValue(node,
				// "name");
				// if (columnAlias != null && !columnAlias.equals("")) {
				// SaturnMappingRule source = new SaturnMappingRule();
				// source.setKey(columnAlias);
				// mappingTarget.add(source);
				// } else {
				// SaturnMappingRule source = new SaturnMappingRule();
				// source.setKey(name);
				// mappingTarget.add(source);
				// }
				// }
				// tableViewer1.setInput(mappingTarget);
				// }
				// }
				// });
				OneCompontentSearchDialog dialog = new OneCompontentSearchDialog(
						getShell(), shape);

				if (dialog.open() == Window.OK) {
					SearchResult value = (SearchResult) dialog.getFirstResult();
					textTargetKey.setText(value.getKey());

					setErrorMessage(null);
					getButton(IDialogConstants.OK_ID).setEnabled(true);
					Document doucument = value.getDocument();
					Node dataNode = SaturnW3CUtil.getFirstChildByName(doucument
							.getDocumentElement(), "data");
					Node fieldsNode = SaturnW3CUtil.getFirstChildByName(
							dataNode, "fields");
					List<Node> list = SaturnW3CUtil.getChildrenNode(fieldsNode);
					mappingTarget.removeAll(mappingTarget);
					for (Node node : list) {
						String columnAlias = SaturnW3CUtil
								.getNodeAttributeValue(node, "columnAlias");
						String name = SaturnW3CUtil.getNodeAttributeValue(node,
								"name");
						if (columnAlias != null && !columnAlias.equals("")) {
							SaturnMappingRule source = new SaturnMappingRule();
							source.setKey(columnAlias);
							mappingTarget.add(source);
						} else {
							SaturnMappingRule source = new SaturnMappingRule();
							source.setKey(name);
							mappingTarget.add(source);
						}
					}
					tableViewer1.setInput(mappingTarget);
				}

			}
		});

		final Label label_1 = new Label(container, SWT.NONE);
		final GridData gd_label_1 = new GridData();
		gd_label_1.verticalIndent = 5;
		label_1.setLayoutData(gd_label_1);
		label_1.setText(Messages.getString("SaturnDataMappingDialog.source")); //$NON-NLS-1$

		comboSource = new Combo(container, SWT.NONE);
		comboSource.setTextLimit(100);
		comboSource.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				textSourceKey.setText("");
				List<SaturnMappingRule> temp = new ArrayList<SaturnMappingRule>();
				tableViewer.setInput(temp);
			}
		});
		final GridData gd_comboSource = new GridData(SWT.RIGHT, SWT.CENTER,
				false, false);
		gd_comboSource.widthHint = 280;
		gd_comboSource.verticalIndent = 5;
		comboSource.setLayoutData(gd_comboSource);
		comboSource.setItems(getParameterInForInout());

		final Label label_2 = new Label(container, SWT.NONE);
		final GridData gd_label_2 = new GridData();
		gd_label_2.verticalIndent = 5;
		label_2.setLayoutData(gd_label_2);
		label_2.setText(Messages
				.getString("SaturnDataMappingDialog.SourceFullKey")); //$NON-NLS-1$

		textSourceKey = new Text(container, SWT.BORDER);
		textSourceKey.setTextLimit(100);
		final GridData gd_textSourceKey = new GridData(SWT.FILL, SWT.CENTER,
				true, false);
		gd_textSourceKey.widthHint = 280;
		gd_textSourceKey.verticalIndent = 5;
		textSourceKey.setLayoutData(gd_textSourceKey);
		// this.textSourceKey.setText(shape.getFullkey());

		final Label browseSouce = new Label(container, SWT.NONE);
		browseSouce.setImage(Activator.getImage(Images.AMPLIFY_PLUS));
		final GridData gd_browseSouce = new GridData();
		gd_browseSouce.verticalIndent = 5;
		browseSouce.setLayoutData(gd_browseSouce);
		browseSouce.addMouseListener(new MouseAdapter() {
			public void mouseDown(final MouseEvent e) {
				// ElementListSelectionDialog dialog1 = new
				// ElementListSelectionDialog(
				// Display.getDefault().getShells()[0],
				// new SaturnSWTUtils.SaturnLabelDefaultProvider());
				//
				// ElementListSelectionDialog projectsDialog = new
				// ElementListSelectionDialog(
				// Display.getDefault().getShells()[0],
				// new SaturnSWTUtils.SaturnLabelDefaultProvider());
				// IProject projects[] =
				// ResourcesPlugin.getWorkspace().getRoot()
				// .getProjects();
				// projectsDialog.setTitle(Messages.getString("SaturnDataMappingDialog.ChooseOneProject"));
				// //$NON-NLS-1$
				// List<String> projectsName = new ArrayList<String>();
				//
				// for (IProject project : projects) {
				// projectsName.add(project.getName());
				// }
				//
				// projectsDialog.setElements(projectsName
				// .toArray(new String[] {}));
				//
				// if (projectsDialog.open() == Window.CANCEL) {
				// return;
				// }
				//
				// project = (String) projectsDialog.getFirstResult();
				// if (project == null || project.equals("")) {
				// return;
				// }
				//
				// IRunnableWithProgress op = new IRunnableWithProgress() {
				// public void run(IProgressMonitor monitor)
				// throws InvocationTargetException {
				// monitor.beginTask("please wait", 100);
				// GUIUpdater g = new GUIUpdater(monitor);
				// Thread t = new Thread(g);
				// sqldata = null;
				// t.start();
				// sqldata = SearchFile.searchFileInproject(
				// ResourcesPlugin.getWorkspace().getRoot()
				// .getProject(project), parameter);
				// }
				// };
				// try {
				// new ProgressMonitorDialog(getShell()).run(true, false, op);
				// } catch (Exception e1) {
				// }
				//
				// Map<String, List<Node>> map = findSaturnData(sqldata);
				// Set<String> set = map.keySet();
				// dialog1.setElements(set.toArray(new String[0]));
				// if (dialog1.open() == Window.OK) {
				// String ddd = (String) dialog1.getFirstResult();
				// textSourceKey.setText(ddd);
				// List<Node> list = map.get(ddd);
				// mappingSources.removeAll(mappingSources);
				// List<SaturnMappingRule> temp = (List<SaturnMappingRule>)
				// tableViewer1
				// .getInput();
				// for (Node node : list) {
				// String columnAlias = SaturnW3CUtil
				// .getNodeAttributeValue(node, "columnAlias");
				// String name = SaturnW3CUtil.getNodeAttributeValue(node,
				// "name");
				// SaturnMappingRule source = new SaturnMappingRule();
				//
				// if (columnAlias != null && !columnAlias.equals("")) {
				// source.setSource(columnAlias);
				// } else {
				// source.setSource(name);
				// }
				//
				// if (buttonAuto.getSelection()) {
				// // 源相同，自动赋值
				// if (temp != null) {
				// for (SaturnMappingRule r : temp) {
				// if (r.getKey().equals(source.getSource())
				// && r.getValue().equals("")
				// && r.getSource().equals("")
				// && r.getFullkey().equals("")) {
				// r.setValue(source.getSource());
				// r.setSource(comboSource.getText()
				// .trim());
				// r.setFullkey(textSourceKey.getText()
				// .trim());
				// }
				// }
				// }
				// }
				// mappingSources.add(source);
				// }
				//
				// tableViewer.setInput(mappingSources);
				// tableViewer1.refresh();
				// }
				// }
				// });
				OneCompontentSearchDialog dialog = new OneCompontentSearchDialog(
						getShell(), shape);

				if (dialog.open() == Window.OK) {
					SearchResult value = (SearchResult) dialog.getFirstResult();
					textSourceKey.setText(value.getKey());

					setErrorMessage(null);
					getButton(IDialogConstants.OK_ID).setEnabled(true);
					Document doucument = value.getDocument();
					Node dataNode = SaturnW3CUtil.getFirstChildByName(doucument
							.getDocumentElement(), "data");
					Node fieldsNode = SaturnW3CUtil.getFirstChildByName(
							dataNode, "fields");
					List<Node> list = SaturnW3CUtil.getChildrenNode(fieldsNode);
					mappingSources.removeAll(mappingSources);
					List<SaturnMappingRule> temp = (List<SaturnMappingRule>) tableViewer1
							.getInput();
					for (Node node : list) {
						String columnAlias = SaturnW3CUtil
								.getNodeAttributeValue(node, "columnAlias");
						String name = SaturnW3CUtil.getNodeAttributeValue(node,
								"name");

						SaturnMappingRule source = new SaturnMappingRule();

						if (columnAlias != null && !columnAlias.equals("")) {

							source.setSource(columnAlias);
						} else {

							source.setSource(name);
						}

						if (buttonAuto.getSelection()) {
							// 源相同，自动赋值
							if (temp != null) {
								for (SaturnMappingRule r : temp) {
									if (r.getKey().equals(source.getSource())
											&& r.getValue().equals("")
											&& r.getSource().equals("")
											&& r.getFullkey().equals("")) {
										r.setValue(source.getSource());
										r.setSource(comboSource.getText()
												.trim());
										r.setFullkey(textSourceKey.getText()
												.trim());
									}
								}
							}
						}
						mappingSources.add(source);
					}
				}
				tableViewer.setInput(mappingSources);
				tableViewer1.refresh();
			}
		});
		browseSouce.addMouseTrackListener(new MouseTrackAdapter() {
			public void mouseEnter(final MouseEvent e) {
				browseSouce.setImage(Activator.getImage(Images.AMPLIFY_MINUS));
			}

			public void mouseExit(final MouseEvent e) {
				browseSouce.setImage(Activator.getImage(Images.AMPLIFY_PLUS));
			}
		});
		browseSouce.addMouseTrackListener(new MouseTrackAdapter() {
			public void mouseEnter(final MouseEvent e) {
				browseSouce.setImage(Activator.getImage(Images.AMPLIFY_MINUS));
			}

			public void mouseExit(final MouseEvent e) {
				browseSouce.setImage(Activator.getImage(Images.AMPLIFY_PLUS));
			}
		});

		final Label label_3 = new Label(container, SWT.NONE);
		label_3.setText(Messages
				.getString("SaturnDataMappingDialog.EvaluateMode")); //$NON-NLS-1$

		final Composite composite = new Composite(container, SWT.NONE);
		composite.setLayoutData(new GridData(257, 33));
		final GridLayout gridLayout_1 = new GridLayout();
		gridLayout_1.numColumns = 2;
		composite.setLayout(gridLayout_1);

		buttonAuto = new Button(composite, SWT.RADIO);
		final GridData gd_buttonAuto = new GridData();
		gd_buttonAuto.verticalIndent = 4;
		buttonAuto.setLayoutData(gd_buttonAuto);
		buttonAuto.setText(Messages.getString("SaturnDataMappingDialog.Auto")); //$NON-NLS-1$

		buttonUserDefine = new Button(composite, SWT.RADIO);
		final GridData gd_buttonUserDefine = new GridData();
		gd_buttonUserDefine.verticalIndent = 4;
		buttonUserDefine.setLayoutData(gd_buttonUserDefine);
		buttonUserDefine.setText(Messages
				.getString("SaturnDataMappingDialog.UserDisicion")); //$NON-NLS-1$
		new Label(container, SWT.NONE);
		new Label(container, SWT.NONE);
		new Label(container, SWT.NONE);
		new Label(container, SWT.NONE);

		tableViewer = new TableViewer(container, SWT.FULL_SELECTION
				| SWT.BORDER);
		tableViewer.addDoubleClickListener(new IDoubleClickListener() {
			@SuppressWarnings("unchecked")
			public void doubleClick(final DoubleClickEvent event) {
				IStructuredSelection selection = (IStructuredSelection) tableViewer1
						.getSelection();
				if (!selection.isEmpty()) {
					IStructuredSelection selectionForSource = (IStructuredSelection) tableViewer
							.getSelection();
					SaturnMappingRule saturn = (SaturnMappingRule) selectionForSource
							.getFirstElement();
					SaturnMappingRule mapping = (SaturnMappingRule) selection
							.getFirstElement();
					mapping.setValue(saturn.getSource());
					mapping.setSource(comboSource.getText());
					mapping.setFullkey(textSourceKey.getText());
					tableViewer1.refresh();
					tableViewer.setSelection(null);
					tableViewer1.setSelection(null);
				}
			}
		});
		table = tableViewer.getTable();
		table.setLinesVisible(true);
		table.setHeaderVisible(true);
		final GridData gd_table = new GridData(SWT.FILL, SWT.FILL, true, true);
		gd_table.verticalIndent = 5;
		gd_table.heightHint = 88;
		table.setLayoutData(gd_table);

		final TableColumn newColumnTableColumn = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				tableViewer
						.setInput(sortListForSaturnMappingRuleSource(((List<SaturnMappingRule>) tableViewer
								.getInput())));
			}
		});
		newColumnTableColumn.setWidth(302);
		newColumnTableColumn.setText(Messages
				.getString("SaturnDataMappingDialog.AttributeName")); //$NON-NLS-1$

		final Button button = new Button(container, SWT.NONE);
		button.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				IStructuredSelection selectionForSource = (IStructuredSelection) tableViewer
						.getSelection();
				IStructuredSelection selection = (IStructuredSelection) tableViewer1
						.getSelection();
				if (!selectionForSource.isEmpty() && !selection.isEmpty()) {
					SaturnMappingRule saturn = (SaturnMappingRule) selectionForSource
							.getFirstElement();
					SaturnMappingRule mapping = (SaturnMappingRule) selection
							.getFirstElement();
					mapping.setValue(saturn.getSource());
					mapping.setSource(comboSource.getText());
					mapping.setFullkey(textSourceKey.getText());
					tableViewer1.refresh();
					tableViewer.setSelection(null);
					tableViewer1.setSelection(null);
				} else if (selectionForSource.isEmpty() && !selection.isEmpty()) {
					SaturnMappingRule mapping = (SaturnMappingRule) selection
							.getFirstElement();
					mapping.setSource(comboSource.getText());
					mapping.setFullkey(textSourceKey.getText());
					tableViewer1.refresh();
					tableViewer.setSelection(null);
					tableViewer1.setSelection(null);
				} else {
					MessageDialog.openInformation(null,
							SelectionCandidate.HINT,
							SelectionCandidate.CHOOSE_A_RECORD);
				}
			}
		});
		button.setText(Messages.getString("SaturnDataMappingDialog.evaluate")); //$NON-NLS-1$

		tableViewer1 = new TableViewer(container, SWT.MULTI
				| SWT.FULL_SELECTION | SWT.BORDER);
		table_1 = tableViewer1.getTable();
		table_1.setLinesVisible(true);
		table_1.setHeaderVisible(true);
		final GridData gd_table_1 = new GridData(SWT.FILL, SWT.FILL, true, true);
		gd_table_1.heightHint = 91;
		gd_table_1.verticalIndent = 5;
		table_1.setLayoutData(gd_table_1);

		final TableColumn newColumnTableColumn_1 = new TableColumn(table_1,
				SWT.NONE);
		newColumnTableColumn_1.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				tableViewer1
						.setInput(sortList(((List<SaturnMappingRule>) tableViewer1
								.getInput())));
			}
		});
		newColumnTableColumn_1.setWidth(100);
		newColumnTableColumn_1.setText(Messages
				.getString("SaturnDataMappingDialog.TargetAttribute")); //$NON-NLS-1$

		final TableColumn newColumnTableColumn_2 = new TableColumn(table_1,
				SWT.NONE);
		newColumnTableColumn_2.setWidth(100);
		newColumnTableColumn_2.setText(Messages
				.getString("SaturnDataMappingDialog.SourceValue")); //$NON-NLS-1$

		final TableColumn newColumnTableColumn_3 = new TableColumn(table_1,
				SWT.NONE);
		newColumnTableColumn_3.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				tableViewer1
						.setInput(sortListForSaturnMappingRuleSource(((List<SaturnMappingRule>) tableViewer1
								.getInput())));
			}
		});
		newColumnTableColumn_3.setWidth(100);
		newColumnTableColumn_3.setText(Messages
				.getString("SaturnDataMappingDialog.Source")); //$NON-NLS-1$

		tableViewer1.setContentProvider(new TableViewerContentProvider());
		tableViewer1.setLabelProvider(new TableViewerTargetLableProvider());
		this.tableViewer1.setInput(this.mappingTarget);

		final Button button_1 = new Button(container, SWT.NONE);
		button_1.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				IStructuredSelection selectionForSource = (IStructuredSelection) tableViewer1
						.getSelection();
				if (selectionForSource.isEmpty()) {
					MessageDialog.openInformation(null,
							SelectionCandidate.HINT,
							SelectionCandidate.CHOOSE_A_RECORD);
				} else if (!selectionForSource.isEmpty()) {
					Iterator<SaturnMappingRule> it = selectionForSource
							.iterator();
					for (; it.hasNext();) {
						SaturnMappingRule saturn = it.next();
						saturn.setFullkey("");
						saturn.setSource("");
						saturn.setValue("");
					}
				}
				tableViewer1.refresh();
			}
		});
		button_1.setText(Messages.getString("SaturnDataMappingDialog.clear")); //$NON-NLS-1$

		tableViewer.setContentProvider(new TableViewerContentProvider());
		tableViewer.setLabelProvider(new TableViewerLableProvider());

		String[] valueKeys = this.getParameterInForInout();

		comboSource.setItems(getParameterValue());
		comboTarget.setItems(valueKeys);
		
		
		this.idText.setText(shape.getId().trim());
		this.textName.setText(shape.getName().trim());
		this.textName.setSelection(shape.getName().trim().length());
		// for(SaturnMappingRule rule : mappingTarget){
		// if(!rule.getSource().equals("")){
		// this.comboSource.setText(rule.getSource());
		// }
		// }
		text.setText(this.shape.getDescription());
		this.comboTarget.setText(this.shape.getValuekey());

		/**
		 * 名称，Target FullKey不可为空判断
		 * 
		 */
		if ("".equals(textTargetKey.getText().trim())) {
			setErrorMessage(Messages
					.getString("SaturnDataMappingDialog.TargetFullKeyLimit")); //$NON-NLS-1$
		}

		textName.addModifyListener(new ModifyListener() {
			public void modifyText(final ModifyEvent e) {
				validate();
			}
		});

		textTargetKey.addModifyListener(new ModifyListener() {
			public void modifyText(final ModifyEvent e) {
				validate();
			}
		});
		buttonUserDefine.setSelection(true);
		buttonAuto.setSelection(false);
		setTitleImage(Activator.getImage(Images.SATURN_ICONS_MAXNAME));

		return area;
	}

	/**
	 * 文本框空值判断
	 * 
	 */
	private void validate() {
		String name = textName.getText().trim();
		String fullTargetKey = textTargetKey.getText().trim();
		
		if (SaturnValidation.isEmpty(name)) {
			setErrorMessage(Messages
					.getString("SaturnDataMappingDialog.NameLimit")); //$NON-NLS-1$
			getButton(IDialogConstants.OK_ID).setEnabled(false);
		} else if (SaturnValidation.isEmpty(fullTargetKey)) {
			setErrorMessage(Messages
					.getString("SaturnDataMappingDialog.TargetFullKeyLimit")); //$NON-NLS-1$
			getButton(IDialogConstants.OK_ID).setEnabled(false);
		} else {
			setErrorMessage(null);
			getButton(IDialogConstants.OK_ID).setEnabled(true);
		}
	}

	// /**
	// * 判断文本框内容是否为空
	// */
	// private boolean isEmpty(String str) {
	// boolean isEmpty = false;
	// if (str == null || str.trim().length() == 0) {
	// isEmpty = true;
	// }
	// return isEmpty;
	// }

	private String[] getParameterInForInout() {
		Set<String> list = new HashSet<String>();
		ShapesDiagram diagrame = (ShapesDiagram) shape.getParent();
		List<Shape> shapes = diagrame.getShapes();
		for (Shape allShape : shapes) {
			List<SaturnParameter> parameters = allShape.getParameters();
			for (SaturnParameter parameter : parameters) {
				if (parameter.getClassType().equals(
						"edu.ccut.saturn.component.SaturnData")) {
					list.add(parameter.getValueKey());
				}
			}
		}
		return list.toArray(new String[0]);
	}

	private String[] getParameterValue() {
		Set<String> list = new HashSet<String>();
		ShapesDiagram diagrame = (ShapesDiagram) shape.getParent();
		List<Shape> shapes = diagrame.getShapes();
		for (Shape allShape : shapes) {
			List<SaturnParameter> parameters = allShape.getParameters();
			for (SaturnParameter parameter : parameters) {
				String parameterValue = parameter.getValueKey();
				list.add(parameterValue);
			}
		}
		return list.toArray(new String[0]);
	}

	private Map<String, List<Node>> findSaturnData(List<Document> list) {
		Map<String, List<Node>> dataMap = new HashMap<String, List<Node>>();

		for (Document doc : list) {
			NodeList nodeList = doc.getElementsByTagName("data");
			for (int i = 0; i < nodeList.getLength(); i++) {
				Node node = nodeList.item(i);
				String fullkey = SaturnW3CUtil.getNodeAttributeValue(node,
						"namespace")
						+ "::"
						+ SaturnW3CUtil.getNodeAttributeValue(node, "name");
				NodeList nodeFiels = node.getChildNodes();
				List<Node> fielList = new ArrayList<Node>();
				for (int j = 0; j < nodeFiels.getLength(); j++) {
					Node fiel = nodeFiels.item(j);
					if (fiel.getNodeName().equals("fields")) {
						NodeList nl = fiel.getChildNodes();
						for (int k = 0; k < nl.getLength(); k++) {
							Node n = nl.item(k);
							if (n.getNodeName().equals("field")) {
								fielList.add(n);
							}
						}
					}
				}
				dataMap.put(fullkey, fielList);
			}
		}
		return dataMap;
	}

	protected void buttonPressed(int buttonId) {
		if (buttonId == IDialogConstants.OK_ID) {

			this.shape.setName(this.textName.getText());
			this.shape.setFullkey(this.textTargetKey.getText());
			this.shape.setValuekey(this.comboTarget.getText());
			this.shape.setSaturnMappingRules(this.mappingTarget);
			this.shape.setDescription(text.getText().trim());
		}
		super.buttonPressed(buttonId);
	}

	@Override
	protected void createButtonsForButtonBar(Composite parent) {
		createButton(parent, IDialogConstants.OK_ID, Messages
				.getString("ManageConnectionDialog.confirm"), false); //$NON-NLS-1$
		createButton(parent, IDialogConstants.CANCEL_ID, Messages
				.getString("ManageConnectionDialog.cancel"), false); //$NON-NLS-1$
		getButton(IDialogConstants.OK_ID).setEnabled(
				!("".equals(textTargetKey.getText().trim())));
	}

	// private String cutTargetKey(String key){
	// int i = key.indexOf("::");
	// String temp = key.substring(0,i);
	// return temp;
	// }

	private List<SaturnMappingRule> copyList(List<SaturnMappingRule> list) {
		List<SaturnMappingRule> tempList = new ArrayList<SaturnMappingRule>();
		for (SaturnMappingRule rule : list) {
			tempList.add(new SaturnMappingRule(rule));
		}
		return tempList;
	}

	protected int getShellStyle() {
		return SWT.CLOSE | SWT.RESIZE;
	}

	protected Point getInitialSize() {
		return new Point(800, 713);
	}

	class GUIUpdater implements Runnable {
		private IProgressMonitor monitor;

		GUIUpdater(IProgressMonitor monitor) {
			this.monitor = monitor;
		}

		public void run() {
			for (int i = 0; i < 34; i++) {
				try {
					Thread.sleep(500);
					this.monitor.worked(5);
					if (sqldata != null) {
						this.monitor.worked(100);
						break;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

	// 对表格1 源进行排序

	private List<SaturnMappingRule> sortList(List<SaturnMappingRule> tempList) {
		List<SaturnMappingRule> list = new ArrayList<SaturnMappingRule>();

		for (int i = 0; i < tempList.size(); i++) {
			if (list.size() == 0) {
				list.add(tempList.get(i));
			} else {
				SaturnMappingRule project = tempList.get(i);
				String projectName = project.getKey().substring(0, 1);
				int j = this.getListLocation(list, projectName);
				if (j != -1) {
					list.add(j + 1, project);
				} else {
					list.add(0, project);
				}
			}
		}
		return list;
	}

	private int getListLocation(List<SaturnMappingRule> list, String oldValue) {
		int j = -1;
		for (int i = 0; i < list.size(); i++) {
			SaturnMappingRule project = list.get(i);
			String newValue = project.getKey().substring(0, 1);
			if (newValue.compareToIgnoreCase(oldValue) < 0) {
				j = i;
			}
		}
		return j;
	}

	private List<SaturnMappingRule> sortListForSaturnMappingRuleSource(
			List<SaturnMappingRule> tempList) {
		List<SaturnMappingRule> list = new ArrayList<SaturnMappingRule>();

		for (int i = 0; i < tempList.size(); i++) {
			if (list.size() == 0) {
				list.add(tempList.get(i));
			} else {
				SaturnMappingRule project = tempList.get(i);
				String projectName = "";
				if (!project.getSource().equals("")) {
					projectName = project.getSource().substring(0, 1);
					int j = this.getListLocationForSaturnMappingRuleSource(list,
							projectName);
					if (j != -1) {
						list.add(j + 1, project);
					} else {
						list.add(0, project);
					}
				}
			}
		}

		for (SaturnMappingRule rule : tempList) {
			if (rule.getSource().equals("")) {
				list.add(rule);
			}
		}
		return list;
	}

	private int getListLocationForSaturnMappingRuleSource(
			List<SaturnMappingRule> list, String oldValue) {
		int j = -1;
		for (int i = 0; i < list.size(); i++) {
			SaturnMappingRule project = list.get(i);
			if (project.getSource().equals("")) {
				return j;
			}
			String newValue = project.getSource().substring(0, 1);
			if (newValue.compareToIgnoreCase(oldValue) < 0) {
				j = i;
			}
		}
		return j;
	}

	protected void configureShell(Shell newShell) {
		super.configureShell(newShell);
		newShell.setImage(Activator.getImage(Images.SATURN_ICONS_SMALLNAME));
		newShell.setText(Messages.getString("SaturnDataMappingDialog.SetParameter")); //$NON-NLS-1$
	}
}